﻿using Cl.Entity.DataBaseEntity.User;
using Cl.Model.DataBaseEntityDtos.User.Permissions;
using Cl.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cl.Service.Service.User.Permissions
{
    public class PermissionService : ClRepository<Permission>, IPermissionService
    {
        #region 依赖注入


        private ClRepository<UserRole> _userRoleRepository;
        private ClRepository<RolePermission> _rolePermissionRoleRepository;
        private ClRepository<Permission> _permissionRepository;


        /// <summary>
        /// 构造函数
        /// </summary>
        public PermissionService(ClRepository<UserRole> userRoleRepository, ClRepository<RolePermission> rolePermissionRoleRepository,
             ClRepository<Permission> permissionRepository)
        {
            _userRoleRepository = userRoleRepository;
            _rolePermissionRoleRepository = rolePermissionRoleRepository;
            _permissionRepository = permissionRepository;

        }

        #endregion

        public List<PermissionOutDto> GetMenusList()
        {
            return _permissionRepository.AsQueryable()
                .Where(x => x.Enabled == true)
                .Select(x => new PermissionOutDto(x) { }).ToList();
        }

        public List<PermissionOutDto> GetUserMenus(int accountId)
        {
            List<PermissionOutDto> result = new List<PermissionOutDto>();

            var userRole = _userRoleRepository.AsQueryable();
            var rolePermission = _rolePermissionRoleRepository.AsQueryable();
            var permission = _permissionRepository.AsQueryable();

            var A = userRole.ToList();
            var b = rolePermission.ToList();
            var c = permission.ToList();

            var userRolePermission = userRole.Where(x => x.UserId == accountId)
                .LeftJoin(rolePermission, (r, p) => r.RoleId == p.RoleId)
                .LeftJoin(permission, (r, p, per) => p.PermissionId == per.Id)
                .Select((r, p, per) => new PermissionOutDto(per) { })
                .ToList();
            result = userRolePermission;

            return result;
        }
    }
}
